package com.atguigu.gmall.mq.receiver;

import com.atguigu.gmall.mq.config.DeadLetterMqconfig;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description:
 * @author: JC
 * @date: 2021/11/10 19:33
 */
@Component
@Slf4j
public class ConfirmReceiver {

    @RabbitListener(queues = {DeadLetterMqconfig.QUEUE_DEAD_2})
    @SneakyThrows
    public void getMessage(String msg, Message message, Channel channel){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());

        System.out.println("接收的消息为： = " + msg + "，\n时间为：" + format);
        // 确认ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    // 监听获取消息！ 需要设置绑定参数
    // @RabbitListener()
    @RabbitListener(bindings = @QueueBinding(
                    value = @Queue(value = "queue.confirm",durable = "true", autoDelete = "false"),
                    exchange = @Exchange(value = "exchange.confirm",durable = "true", autoDelete = "false"),
                    key= {"routing.confirm"}
                    ))
    @SneakyThrows
    public void getMsg(String msg, Message message, Channel channel){
        long deliveryTag = 0;
        try {
            System.out.println("获取的消息："+msg);
            System.out.println("获取的消息(Message)："+new String(message.getBody()));
            // 手动确认 ： ack
            deliveryTag = message.getMessageProperties().getDeliveryTag();
            // false: 表示一个一个来确认消息 ，true表示批量确认消息！
            channel.basicAck(deliveryTag,false);
        } catch (IOException e) {
            log.info("rabbitMq监听失败原因:"+e.getMessage());
            // 第三个参数：是否重回队列
            channel.basicNack(deliveryTag,false,true);

        } finally {

        }

    }
}
